package com.medicalproject.controller;

import com.alipay.api.AlipayClient;
import com.medical.pojo.User;
import com.medical.vo.Rmed;
import com.medicalproject.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    RedisTemplate redisTemplate;
@RequestMapping("sendcode")
public Rmed sendcode(@RequestParam String phone){
   return Rmed.suceessData(userService.sendcode(phone));
}
    @RequestMapping("login")
    public Rmed login(@RequestParam String username, @RequestParam String password){
        User user = userService.login(username, password);
        System.out.println(user);
        if (user!=null){
            return Rmed.suceessData(user);
        }else {
            return Rmed.error("用户名或密码错误");
        }
    }
    @RequestMapping("login2")
    public Rmed login2(@RequestParam String phone, @RequestParam String code){
        // 从 Redis 中获取验证码
        String redisCode = (String) redisTemplate.boundValueOps("121212").get();

        // 检查 Redis 中的验证码是否存在
        if (redisCode == null) {
            return Rmed.error("验证码不存在");
        }

        // 将 Redis 中的验证码转换为字符串
        code = redisCode.toString();

        User user = userService.login2(phone, code);

        if (user != null) {
            return Rmed.suceessData(user);
        } else {
            return Rmed.error("验证码错误");
        }

        }

        @RequestMapping("update")
    public void update(@RequestParam String phone,@RequestParam String code){
        userService.update(phone, code);
        }

        @RequestMapping("add")
    public Rmed add(@RequestBody User user,HttpServletResponse response) throws IOException {
            String redisCode = (String) redisTemplate.boundValueOps("121212").get();
            if (user.getCode().equals(redisCode)){
              userService.add(user);
            }else {
                return Rmed.error("验证码错误");
            }
            return Rmed.suceessData("注册成功，欢迎你"+user.getUsername());
        }
    }





